package com.cwz.springboot.crawlerfirst.crawler.get;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;

public class HttpGetParamTest {

    public static void main(String[] args) throws URISyntaxException {


        // 1. 打开浏览器，创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 设置请求地址是：http://106.15.37.148/testdisplay/a.html?name=cwz
        // 创建URIBuilder
        URIBuilder uriBuilder = new URIBuilder("http://10.20.208.11/(obrtrx45ynazkxaxh5cyplni)/xs_main.aspx");
        // 设置参数 .setParameter()一直往后加
        uriBuilder.setParameter("xh", "201635020308");

        // 2. 输入网址，发起get请求并创建HttpGet对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        CloseableHttpResponse response = null;

        try {
            // 3. 按回车，发起请求，返回响应，使用HttpClient对象发起请求
            response = httpClient.execute(httpGet);

            // 4. 解析响应，获取数据
            // 判断状态码是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                String content = EntityUtils.toString(httpEntity, "utf8");
                System.out.println("响应报文的长度：" + content.length());
                System.out.println(content);
                System.out.println("这是传送有参数的HTTPGET请求");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭httpClient和response
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
